package com.cyx.log;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;


@Component
public class LogUtils {

    public static void logStart(JoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        String funcName = joinPoint.getSignature().getName();
        System.out.println(funcName+"("+Arrays.asList(args)+") 开始执行...");
    }

    public static void logSuccessReturn(JoinPoint joinPoint,Object result ){
        Object[] args = joinPoint.getArgs();
        String funcName = joinPoint.getSignature().getName();
        System.out.println(funcName+" 成功返回: "+result);
    }

    public static void logExceptionReturn(JoinPoint joinPoint,Exception e){
        Object[] args = joinPoint.getArgs();
        String funcName = joinPoint.getSignature().getName();
        System.out.println(funcName+" 异常返回:"+e.getMessage());
    }

    public static void logFinal(JoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        String funcName = joinPoint.getSignature().getName();
        System.out.println(funcName+" 最终结束");
    }


    public static Object logAll(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result = null;
        Object[] args = joinPoint.getArgs();
        try {
            System.out.println("环绕通知-开始...");
            //利用反射方法调用
            result = joinPoint.proceed(args);
            System.out.println("环绕通知-正常结束");
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            System.out.println("环绕通知-异常");
        } finally {
            System.out.println("环绕通知-最终结束");
        }
        return result;
    }

}
